const express = require('express');
const router = express.Router();
const tencentIMService = require('../utils/tencent-im');
const logger = require('../utils/logger');

/**
 * @route POST /api/chat/conversation
 * @description 创建或获取聊天会话
 * @body {string} userId1 - 用户1的ID
 * @body {string} userId2 - 用户2的ID
 */
router.post('/conversation', async (req, res) => {
  try {
    const { userId1, userId2 } = req.body;

    // 参数验证
    if (!userId1 || !userId2) {
      return res.status(400).json({
        code: 404,
        error: '用户ID不能为空'
      });
    }

    // 生成会话ID
    const conversationId = tencentIMService.generateConversationId(userId1, userId2);

    logger.info(`创建聊天会话 - 用户: ${userId1} 和 ${userId2}, 会话ID: ${conversationId}`);

    res.json({
      code: 200,
      message: "创建成功",
      data: {
        conversationId,
        userId1,
        userId2,
        type: 'C2C'
      }
    });

  } catch (error) {
    logger.error('创建聊天会话失败:', error);
    
    res.status(500).json({
      code: 404,
      error: error.message
    });
  }
});

/**
 * @route GET /api/chat/conversation/:conversationId
 * @description 获取会话信息
 * @param {string} conversationId - 会话ID
 */
router.get('/conversation/:conversationId', async (req, res) => {
  try {
    const { conversationId } = req.params;

    // 解析会话ID
    const [userId1, userId2] = tencentIMService.parseConversationId(conversationId);

    res.json({
      code: 200,
      message: "获取会话信息成功",
      data: {
        conversationId,
        userId1,
        userId2,
        type: 'C2C'
      }
    });

  } catch (error) {
    logger.error('获取会话信息失败:', error);
    
    res.status(400).json({
      code: 404,
      error: error.message
    });
  }
});

/**
 * @route POST /api/chat/login-info
 * @description 获取用户登录信息（UserSig + 会话信息）
 * @body {string} currentUserId - 当前用户ID
 * @body {string} targetUserId - 对方用户ID
 */
router.post('/login-info', async (req, res) => {
  try {
    const { currentUserId, targetUserId } = req.body;

    // 参数验证
    if (!currentUserId || !targetUserId) {
      return res.status(400).json({
        code: 404,
        error: '用户ID不能为空'
      });
    }

    if (!tencentIMService.isConfigured()) {
      return res.status(503).json({
        code: 404,
        error: '腾讯云IM服务未配置'
      });
    }

    // 生成UserSig
    const userSigData = tencentIMService.generateUserSig(currentUserId);

    // 生成会话ID
    const conversationId = tencentIMService.generateConversationId(currentUserId, targetUserId);

    res.json({
      code: 200,
      message: "获取用户登录信息成功",
      data: {
        userSig: userSigData.userSig,
        sdkAppId: userSigData.sdkAppId,
        userId: currentUserId,
        conversationId,
        targetUserId,
        expireTime: userSigData.expireTime
      }
    });

  } catch (error) {
    logger.error('获取登录信息失败:', error);
    
    res.status(500).json({
      code: 404,
      error: error.message
    });
  }
});

/**
 * @route POST /api/chat/user-status
 * @description 检查用户在线状态和存在性
 * @body {string} targetUserId - 要检查的用户ID
 * @body {string} currentUserId - 当前用户ID（用于验证权限）
 */
router.post('/user-status', async (req, res) => {
  try {
    const { targetUserId, currentUserId } = req.body;

    // 参数验证
    if (!targetUserId) {
      return res.status(400).json({
        code: 400,
        error: '目标用户ID不能为空'
      });
    }

    if (!tencentIMService.isConfigured()) {
      return res.status(503).json({
        code: 503,
        error: '腾讯云IM服务未配置'
      });
    }

    logger.info(`检查用户状态 - 目标用户: ${targetUserId}, 当前用户: ${currentUserId}`);

    // 默认返回用户存在但状态未知（因为需要REST API才能获取实际状态）
    res.json({
      code: 200,
      message: "获取用户状态成功",
      data: {
        userId: targetUserId,
        exists: true, // 假设用户存在，因为无法直接验证
        onlineStatus: 'unknown', // unknown, online, offline
        lastActiveTime: null,
        canBeContacted: true, // 默认可以联系
        reason: '基础状态检查完成',
        suggestedAction: '可以尝试发送消息测试连接'
      }
    });

  } catch (error) {
    logger.error('检查用户状态失败:', error);
    
    res.status(500).json({
      code: 500,
      error: error.message
    });
  }
});

/**
 * @route POST /api/chat/register-user
 * @description 注册用户到腾讯云IM（确保用户存在）
 * @body {string} userId - 用户ID
 * @body {string} nickname - 用户昵称
 */
router.post('/register-user', async (req, res) => {
  try {
    const { userId, nickname = '用户' } = req.body;

    // 参数验证
    if (!userId) {
      return res.status(400).json({
        code: 400,
        error: '用户ID不能为空'
      });
    }

    if (!tencentIMService.isConfigured()) {
      return res.status(503).json({
        code: 503,
        error: '腾讯云IM服务未配置'
      });
    }

    logger.info(`注册用户到腾讯云IM - 用户ID: ${userId}, 昵称: ${nickname}`);

    // 在腾讯云IM中，用户首次使用时会自动注册
    // 这里我们生成UserSig表示用户已准备就绪
    const userSigData = tencentIMService.generateUserSig(userId);

    res.json({
      code: 200,
      message: "用户注册/验证成功",
      data: {
        userId,
        nickname,
        registered: true,
        userSig: userSigData.userSig,
        sdkAppId: userSigData.sdkAppId,
        expireTime: userSigData.expireTime,
        message: '用户已准备就绪，可以开始聊天'
      }
    });

  } catch (error) {
    logger.error('用户注册失败:', error);
    
    res.status(500).json({
      code: 500,
      error: error.message
    });
  }
});

/**
 * @route GET /api/chat/health
 * @description 检查聊天服务健康状态
 */
router.get('/health', async (req, res) => {
  try {
    const config = tencentIMService.getConfig();

    res.json({
      code: 200,
      data: {
        service: 'second-hand-chat-service',
        timestamp: new Date().toISOString(),
        tencentIM: {
          configured: config.isConfigured,
          sdkAppId: config.sdkAppId
        }
      }
    });

  } catch (error) {
    logger.error('检查健康状态失败:', error);
    
    res.status(500).json({
      code: 404,
      error: error.message
    });
  }
});

module.exports = router;